/*
 * @Description: ali-oss
 * @Author: zhangguoliang
 * @Date: 2021-08-19 10:09:03
 * @LastEditors: sunchen
 * @LastEditTime: 2023-08-29 13:55:49
 */

import OSS from 'ali-oss';
class AliOSS {
  options = {
    accessKeyId: import.meta.env.VITE_APP_ALI_OSS_KEY,
    accessKeySecret: import.meta.env.VITE_APP_ALI_OSS_SECRET,
    bucket: import.meta.env.VITE_APP_ALI_OSS_BUCKET,
    secure: true,
    region: import.meta.env.VITE_APP_ALI_OSS_REGION,
  };
  client = new OSS(this.options);
  getDate() {
    const date = new Date();
    return `${date.getFullYear()}${(date.getMonth() + 1)
      .toString()
      .padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}`;
  }
  getRandomStr() {
    return Math.random().toString(36).slice(2);
  }
  async upload(file){
    if (!file) return '';
    let saveAs = `import/${this.getRandomStr()}-${file.name}`;
    if(!["prod"].includes(import.meta.env.MODE)){
      saveAs = `import/${this.getRandomStr()}-${file.name}`;
    }
    const result = await this.client.multipartUpload(saveAs, file, {});
    return this.getDownloadUrl(result);
  }
  getDownloadUrl(result) {
    const uploadFile = result.name;
    // 获取文件url
    const url = this.client.signatureUrl(uploadFile, {
      expires: 3600 * 1000 * 24 * 365 * 100,
      response: {
        'content-disposition': `attachment; filename=${encodeURIComponent(
          uploadFile
        )}`,
      },
    });
    return url.split('?')[0];
  }
  download(name) {
    const url = this.client.signatureUrl(name, {
      expires: 3600,
      response: {
        'content-disposition': `attachment; filename=${name}`,
      },
    });
    window.location.href = url;
  }
}

export default AliOSS;
